// 节流函数
export const throttle = <T extends (...args: any[]) => void>(
    fn: T,
    delay: number
): T => {
    let lastCall = 0
    let timeoutId: ReturnType<typeof setTimeout> | null = null

    return ((...args: Parameters<T>) => {
        const now = Date.now()
        const later = () => {
            lastCall = now
            fn(...args)
        }

        if (timeoutId) clearTimeout(timeoutId)

        if (now - lastCall >= delay) {
            later()
        } else {
            timeoutId = setTimeout(later, delay - (now - lastCall))
        }
    }) as T
}
// 防抖函数
export const debounce = <T extends (...args: any[]) => void>(
    fn: T,
    delay: number,
    immediate = false
): T => {
    let timeoutId: ReturnType<typeof setTimeout> | null = null

    return ((...args: Parameters<T>) => {
        const callNow = immediate && !timeoutId

        if (timeoutId) clearTimeout(timeoutId)

        timeoutId = setTimeout(() => {
            if (!immediate) fn(...args)
            timeoutId = null
        }, delay)

        if (callNow) fn(...args)
    }) as T
}